import {useEditor, useSlate} from "slate-react";
import {useCallback} from "react";
import {Editor, Transforms} from "slate";
import {Button} from "antd";

const isMarkActive = (editor, format) => {
  const marks = Editor.marks(editor);
  return marks ? marks[format] === true : false
};

export default (props) => {
  const {mark, children} = props;
  const slate = useSlate();
  const editor = useEditor();
  const isActive = useCallback(() => {
    return isMarkActive(slate, mark);
  }, [slate, mark]);

  const handleClick = useCallback(() => {
    const { selection } = editor;
    const active = isActive();
    if (!active && selection) {
      // const text = Editor.string(editor, selection);
      // editor.insertText(`${text}`);
      // Transforms.select(editor, selection);
      editor.addMark(mark, true);
      Transforms.collapse(editor, {
        edge: 'focus'
      });
      return;
    }

    if (selection) {
      // // 快捷取消mark
      // if (Range.isCollapsed(selection)) {
      //   Transforms.unsetNodes(editor, 'code', {
      //     match: Text.isText,
      //     at: selection.focus.path,
      //   })
      // } else {
      //   editor.removeMark('code')
      // }
      editor.removeMark(mark)
    }
  }, [mark, isActive, editor]);

  return (
    <>
      <Button onClick={handleClick} type={isActive() ? 'primary': ''} size={"small"}>
        {children}
      </Button>
    </>
  )
}
